<?php

namespace app\modules\v1\controllers;

use app\modules\v1\components\BaseController;
use common\models\db\CommercialLoanDetail;
use common\models\db\EqualResult;
use common\models\db\FundLoanDetail;
use common\models\db\LoanRecord;
use common\models\db\PrincipalResult;
use Yii;
use yii\db\Exception;

/**
 * 历史记录相关接口
 */
class HistoryController extends BaseController
{
    /**
     * 保存计算记录 API
     * @return void
     */
    public function actionSave()
    {
        if (!$this->user) {
            $this->error('用户未登录', 401);
        }
        
        // 获取请求参数
        $params = $this->getPostData('params', []);
        $results = $this->getPostData('results', []);
        
        if (empty($params) || empty($results)) {
            $this->error('参数错误', 400);
        }
        
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        
        try {
            // 创建贷款记录
            $record = new LoanRecord();
            $record->user_id = $this->user->id;
            $record->loan_type = $params['type'];
            $record->repayment_type = $params['repaymentType'];
            $record->years = $params['years'];
            $record->total_amount = $results['totalAmount'];
            $record->created_at = date('Y-m-d H:i:s');
            
            if (!$record->save()) {
                throw new Exception('保存贷款记录失败');
            }
            
            // 根据贷款类型保存详情
            if ($params['type'] == 'commercial') {
                $commercial = new CommercialLoanDetail();
                $commercial->record_id = $record->id;
                $commercial->amount = $params['amount'];
                $commercial->rate = $params['rate'];
                $commercial->basis_points = isset($params['basisPoints']) ? $params['basisPoints'] : 0;
                $commercial->adjusted_rate = $results['adjustedRate'];
                
                if (!$commercial->save()) {
                    throw new Exception('保存商业贷款详情失败');
                }
            } else if ($params['type'] == 'fund') {
                $fund = new FundLoanDetail();
                $fund->record_id = $record->id;
                $fund->amount = $params['amount'];
                $fund->rate = $params['rate'];
                
                if (!$fund->save()) {
                    throw new Exception('保存公积金贷款详情失败');
                }
            } else if ($params['type'] == 'combined') {
                $commercial = new CommercialLoanDetail();
                $commercial->record_id = $record->id;
                $commercial->amount = $params['commercialAmount'];
                $commercial->rate = $params['commercialRate'];
                $commercial->basis_points = isset($params['commercialBasisPoints']) ? $params['commercialBasisPoints'] : 0;
                $commercial->adjusted_rate = $results['adjustedCommercialRate'];
                
                if (!$commercial->save()) {
                    throw new Exception('保存商业贷款详情失败');
                }
                
                $fund = new FundLoanDetail();
                $fund->record_id = $record->id;
                $fund->amount = $params['fundAmount'];
                $fund->rate = $params['fundRate'];
                
                if (!$fund->save()) {
                    throw new Exception('保存公积金贷款详情失败');
                }
            }
            
            // 保存等额本息结果
            if (isset($results['equalResult'])) {
                $equal = new EqualResult();
                $equal->record_id = $record->id;
                $equal->total_loan = $results['equalResult']['totalLoan'];
                $equal->total_repayment = $results['equalResult']['totalRepayment'];
                $equal->total_interest = $results['equalResult']['totalInterest'];
                $equal->monthly_payment = $results['equalResult']['monthlyPayment'];
                
                if (!$equal->save()) {
                    throw new Exception('保存等额本息结果失败');
                }
            }
            
            // 保存等额本金结果
            if (isset($results['principalResult'])) {
                $principal = new PrincipalResult();
                $principal->record_id = $record->id;
                $principal->total_loan = $results['principalResult']['totalLoan'];
                $principal->total_repayment = $results['principalResult']['totalRepayment'];
                $principal->total_interest = $results['principalResult']['totalInterest'];
                $principal->first_month_payment = $results['principalResult']['firstMonthPayment'];
                $principal->decrease_per_month = $results['principalResult']['decreasePerMonth'];
                $principal->last_month_payment = $results['principalResult']['lastMonthPayment'];
                
                if (!$principal->save()) {
                    throw new Exception('保存等额本金结果失败');
                }
            }
            
            $transaction->commit();
            
            $this->success(['recordId' => $record->id], '保存成功');
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->error('保存记录失败: ' . $e->getMessage(), 3002);
        }
    }
    
    /**
     * 获取历史记录列表 API
     * @return void
     */
    public function actionList()
    {
        if (!$this->user) {
            $this->error('用户未登录', 401);
        }
        
        $page = intval(Yii::$app->request->get('page', 1));
        $pageSize = intval(Yii::$app->request->get('pageSize', 10));
        
        if ($page < 1) {
            $page = 1;
        }
        
        if ($pageSize < 1 || $pageSize > 100) {
            $pageSize = 10;
        }
        
        // 查询总记录数
        $total = LoanRecord::find()->where(['user_id' => $this->user->id])->count();
        
        // 计算总页数
        $pages = ceil($total / $pageSize);
        
        // 查询当前页的记录
        $records = LoanRecord::find()
            ->where(['user_id' => $this->user->id])
            ->orderBy(['created_at' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->all();
        
        $list = [];
        foreach ($records as $record) {
            // 贷款类型文本
            $loanTypeText = '';
            switch ($record->loan_type) {
                case 'commercial':
                    $loanTypeText = '商业贷款';
                    break;
                case 'fund':
                    $loanTypeText = '公积金贷款';
                    break;
                case 'combined':
                    $loanTypeText = '组合贷款';
                    break;
            }
            
            // 还款方式文本
            $repaymentTypeText = '';
            switch ($record->repayment_type) {
                case 'equal':
                    $repaymentTypeText = '等额本息';
                    break;
                case 'principal':
                    $repaymentTypeText = '等额本金';
                    break;
                case 'compare':
                    $repaymentTypeText = '对比';
                    break;
            }
            
            $list[] = [
                'id' => $record->id,
                'date' => $record->created_at,
                'loanTypeText' => $loanTypeText,
                'totalAmount' => $record->total_amount,
                'years' => $record->years,
                'repaymentTypeText' => $repaymentTypeText
            ];
        }
        
        $data = [
            'total' => $total,
            'pages' => $pages,
            'currentPage' => $page,
            'pageSize' => $pageSize,
            'list' => $list
        ];
        
        $this->success($data, '获取成功');
    }
    
    /**
     * 获取历史记录详情 API
     * @param int $recordId 记录ID
     * @return void
     */
    public function actionDetail($recordId)
    {
        if (!$this->user) {
            $this->error('用户未登录', 401);
        }
        
        // 查询记录
        $record = LoanRecord::findOne($recordId);
        
        if (!$record) {  // || $record->user_id != $this->user->id
            $this->error('记录不存在', 3001);
        }
        
        // 构建返回数据
        $data = [
            'loanType' => $record->loan_type,
            'repaymentType' => $record->repayment_type,
            'years' => $record->years,
            'totalAmount' => $record->total_amount
        ];
        
        // 获取贷款详情
        if ($record->loan_type == 'commercial') {
            $commercial = CommercialLoanDetail::findOne(['record_id' => $record->id]);
            if ($commercial) {
                $data['amount'] = $commercial->amount;
                $data['rate'] = $commercial->rate;
                $data['adjustedRate'] = $commercial->adjusted_rate;
            }
        } else if ($record->loan_type == 'fund') {
            $fund = FundLoanDetail::findOne(['record_id' => $record->id]);
            if ($fund) {
                $data['amount'] = $fund->amount;
                $data['rate'] = $fund->rate;
                $data['adjustedRate'] = $fund->rate;
            }
        } else if ($record->loan_type == 'combined') {
            $commercial = CommercialLoanDetail::findOne(['record_id' => $record->id]);
            $fund = FundLoanDetail::findOne(['record_id' => $record->id]);
            
            if ($commercial) {
                $data['commercialAmount'] = $commercial->amount;
                $data['commercialRate'] = $commercial->rate;
                $data['adjustedCommercialRate'] = $commercial->adjusted_rate;
            }
            
            if ($fund) {
                $data['fundAmount'] = $fund->amount;
                $data['fundRate'] = $fund->rate;
            }
        }
        
        // 获取等额本息结果
        if ($record->repayment_type == 'equal' || $record->repayment_type == 'compare') {
            $equal = EqualResult::findOne(['record_id' => $record->id]);
            if ($equal) {
                $data['equalResult'] = [
                    'totalLoan' => $equal->total_loan,
                    'totalRepayment' => $equal->total_repayment,
                    'totalInterest' => $equal->total_interest,
                    'monthlyPayment' => $equal->monthly_payment
                ];
            }
        }
        
        // 获取等额本金结果
        if ($record->repayment_type == 'principal' || $record->repayment_type == 'compare') {
            $principal = PrincipalResult::findOne(['record_id' => $record->id]);
            if ($principal) {
                $data['principalResult'] = [
                    'totalLoan' => $principal->total_loan,
                    'totalRepayment' => $principal->total_repayment,
                    'totalInterest' => $principal->total_interest,
                    'firstMonthPayment' => $principal->first_month_payment,
                    'decreasePerMonth' => $principal->decrease_per_month,
                    'lastMonthPayment' => $principal->last_month_payment
                ];
            }
        }
        
        // 计算对比结果
        if ($record->repayment_type == 'compare' && isset($data['equalResult']) && isset($data['principalResult'])) {
            $data['interestDiff'] = round($data['equalResult']['totalInterest'] - $data['principalResult']['totalInterest'], 2);
        }
        
        $this->success($data, '获取成功');
    }
    
    /**
     * 删除历史记录 API
     * @param int $recordId 记录ID
     * @return void
     */
    public function actionDelete($recordId)
    {
        if (!$this->user) {
            $this->error('用户未登录', 401);
        }
        
        // 查询记录
        $record = LoanRecord::findOne($recordId);
        
        if (!$record || $record->user_id != $this->user->id) {
            $this->error('记录不存在', 3001);
        }
        
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        
        try {
            // 删除相关数据
            EqualResult::deleteAll(['record_id' => $record->id]);
            PrincipalResult::deleteAll(['record_id' => $record->id]);
            CommercialLoanDetail::deleteAll(['record_id' => $record->id]);
            FundLoanDetail::deleteAll(['record_id' => $record->id]);
            
            // 删除记录
            $record->delete();
            
            $transaction->commit();
            
            $this->success(null, '删除成功');
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->error('删除记录失败: ' . $e->getMessage(), 500);
        }
    }
    
    /**
     * 清空历史记录 API
     * @return void
     */
    public function actionClear()
    {
        if (!$this->user) {
            $this->error('用户未登录', 401);
        }
        
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        
        try {
            // 查询用户的所有记录ID
            $recordIds = LoanRecord::find()
                ->select('id')
                ->where(['user_id' => $this->user->id])
                ->column();
            
            if (!empty($recordIds)) {
                // 删除相关数据
                EqualResult::deleteAll(['record_id' => $recordIds]);
                PrincipalResult::deleteAll(['record_id' => $recordIds]);
                CommercialLoanDetail::deleteAll(['record_id' => $recordIds]);
                FundLoanDetail::deleteAll(['record_id' => $recordIds]);
                
                // 删除记录
                LoanRecord::deleteAll(['user_id' => $this->user->id]);
            }
            
            $transaction->commit();
            
            $this->success(null, '清空成功');
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->error('清空记录失败: ' . $e->getMessage(), 500);
        }
    }
} 